package com.yao.system.websocket.endpoint;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yao.system.entity.dto.UserDTO;
import com.yao.system.util.UserContext;
import com.yao.system.websocket.config.GetHttpSessionConfigurator;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
@ServerEndpoint(value = "/chat/test", configurator = GetHttpSessionConfigurator.class)
public class ChatEndpoint {

    private static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    private UserDTO userDTO;

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        this.userDTO = (UserDTO) config.getUserProperties().get("websocket_session");
        sessionMap.put("userDTO.getName()", session);
    }

    @OnClose
    public void onClose(Session session) {
        sessionMap.remove("userDTO.getName()");
    }

    @OnMessage
    public void onMessage(String message,Session session) {
        UserDTO obj = JSONUtil.toBean(message, UserDTO.class);
        //HashMap<String,UserDTO> map = JSONUtil.toBean(message, HashMap.class);
        System.out.println(obj);
        try {
            Collection<Session> sessions = sessionMap.values();
            for (Session session1 : sessions) {
                session1.getBasicRemote().sendText(JSONUtil.toJsonStr("服务的回复："+message));
                UserDTO dto = new UserDTO();
                dto.setId(1L);
                session1.getBasicRemote().sendText(JSONUtil.toJsonStr(dto));
            }
                session.getBasicRemote().sendText(JSONUtil.toJsonStr("服务的回复："+message));

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(message);

    }

    @OnError
    public void onError(Session session, Throwable throwable) {
    }
}
